package com.jl.core.util;

import cn.hutool.core.collection.CollectionUtil;
import com.jl.utils.MailBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

@Component
public class EmailUtil {

    @Value("${spring.mail.username}")
    private String userName;
    @Resource
    private JavaMailSender javaMailSender;

    public void sendSimpleMail(MailBean mailBean) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(mailBean.getRecipient());
        message.setFrom(userName);
        message.setSubject(mailBean.getSubject());
        message.setText(mailBean.getContent());
        javaMailSender.send(message);
    }

    public void sendAttachmentsMail(MailBean mailBean, List<String> filePath) throws Exception {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(userName);
        helper.setTo(mailBean.getRecipient());
        helper.setSubject(mailBean.getSubject());
        helper.setText(mailBean.getContent(), true);
        if (!CollectionUtil.isEmpty(filePath)){
            for (String path : filePath) {
                FileSystemResource file = new FileSystemResource(new File(path));
                String fileName = file.getFilename();
                helper.addAttachment(fileName, file);
            }
        }
        javaMailSender.send(mimeMessage);
    }


}
